package com.uam.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uam.db.mapper.TaskMapper;
import com.uam.db.model.entity.Task;
import com.uam.web.common.thread.RouteExportThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 航线信息
 * @author uam
 */
@Service
@Slf4j
public class RouteServiceImpl {

    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor executor;

    @Resource
    private TaskMapper taskMapper;
    private long pageSize=20;

    public List<JSONObject> exportData(LocalDateTime start, LocalDateTime end ) throws InterruptedException {

        List<JSONObject> taskVOS = new ArrayList<>();
        IPage<Task> pages=getPageInfo(start,end,0);
        taskVOS.addAll(getTaskVoList(pages.getRecords()));
        long total=pages.getPages();
        if(total >1){
            for(int i=1;i<=total;i++){
                try {
                    taskVOS.addAll(getTaskVoList(getPageInfo(start, end, i).getRecords()));
                }catch (Exception e){
                    log.error("第{}批 查询错误",i);
                }
            }
        }
        return taskVOS;
    }

    private IPage<Task> getPageInfo(LocalDateTime start, LocalDateTime end,int page ){
        LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        taskLambdaQueryWrapper.between(Task::getCreateTime, start, end);
        taskLambdaQueryWrapper.eq(Task::getStatus,4);
        return taskMapper.selectPage(new Page<>(page, pageSize),taskLambdaQueryWrapper);
    }

    private List getTaskVoList(List<Task> tasks) throws InterruptedException {
        List<JSONObject> taskVOS = new ArrayList<>();
        int size=tasks.size();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            executor.execute(new RouteExportThread(countDownLatch,tasks.get(i).getId(),taskVOS));
        }
        countDownLatch.await();
        return taskVOS;
    }
}
